package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.service.CartService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class RemoveCartItemServlet extends HttpServlet {
    private final static String ERROR_FORM =  "/WEB-INF/jsp/common/error.jsp";
    private final static String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        CartService cartService = new CartService();
        CartItem cart= (CartItem)session.getAttribute("cart");
        Account account = (Account)session.getAttribute("loginAccount");
        String workingItemId = req.getParameter("workingItemId");
        String itemId = cartService.removeItemById(account.getUsername(),workingItemId);
        if (itemId == null) {
            session.setAttribute("errorMsg","Attempted to remove null CartItem from Cart.");
            req.getRequestDispatcher(ERROR_FORM).forward(req,resp);

        } else {
            resp.sendRedirect("cartForm");
            //req.getRequestDispatcher(CART_FORM).forward(req,resp);
        }
    }

}
